import Vue from 'vue'
import co from 'co'
// import CommonService from './CommonService'
import * as Util from '../../components/Util'

// 收费冲正
let sellCancelGen = function * (model, row) {
  let result = null
  try {
    // 发卡售气冲正的时候需要清空卡号，为了回滚写卡将卡号暂时保留
    let tempCard_id = {}
    Object.assign(tempCard_id, tempCard_id, row)

    let cardParams
    // 判断是否有卡
    let cardState = yield co(Vue.resetpost('http://127.0.0.1:8003/hasCard', {data: {}}, {resolveMsg: null, rejectMsg: null}))
    if (JSON.parse(cardState.data).state === 1) {
      // 获取气价和售气情况参数
      cardParams = yield co(getParamGen(tempCard_id.f_card_id, row.f_alias))
      // 存库
      result = yield co(cardChargeCancelGen(model, row))
      // 写卡
      if (model.f_canceltype === '超用收费') {
        Vue.showAlert('撤销成功', 'success', 2000)
        return
      }
      let params = {
        factory: row.f_alias,                                // 气表厂家
        kh: tempCard_id.f_card_id,                                   // 卡号
        yhh: row.cardInfo.Meterid,                           // 用户号，档案中自己输
        kmm: row.f_card_password,                            // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
        bjql: row.f_police_gas,                              // 报警气量,t_gasbrand表中
        czsx: row.f_topup_ceil,                              // 充值上线，t_gasbrand表中
        tzed: row.f_overdr_lines,                            // 透支额度，t_gasbrand表中
        bkcs: model.f_replace_time,                          // 补卡次数，从补卡表里通过表编号获得
        ql: '0',                                             // 预购气量
        cs: row.cardInfo.Times - 1,                                     // 求购气次数，先开户为1
        dqdm: '0296',                                          // 精益工业地区代码
        money: '0'                           // 购气金额
      }
      params = Object.assign({}, Vue.CommonService.writeCardParams(cardParams), params)
      let cardRes = yield co(Vue.resetpost('http://127.0.0.1:8003/WriteGasCard', params, {resolveMsg: null, rejectMsg: '冲正卡上气量卡服务错误'}))
      // 卡服务写卡异常，业务逻辑回滚
      if (!cardParams || !result || cardRes.data.Err || cardRes.data.Exception) {
        yield co(rollbackGen(result, model, row))
      } else {
        Vue.showAlert('撤销成功', 'success', 2000)
      }
    } else {
      Vue.showAlert('请检查卡是否插好！！', 'danger', 3000)
    }
  } catch (error) {
    Vue.console.error('出错', error)
    yield co(rollbackGen(result, model, row))
  }
}
// 回滚操作
let rollbackGen = function * (result, model, row) {
  let data = {
    id: result.data.id,
    userfiles: {
      f_user_id: model.f_user_id,
      f_meter_base: row.f_meter_base,
      version: row.version + 1
    },
    changeplus: {
      f_user_id: model.f_user_id,
      f_meter_base: row.f_meter_base + model.f_pregas,
      f_remanent_gas: row.f_remanent_gas - model.f_pregas,
      version: row.version + 1
    },
    table_id: model.id
  }
  return Vue.resetpost('rs/logic/cancelRollback', {data: data}, {resolveMsg: '冲正失败', rejectMsg: '冲正失败'})
}

// 存库操作
let cardChargeCancelGen = function * (model, row) {
  console.log('卡表收费冲正，。。。', model, row)
  let data = {
    cancel: {
      f_user_id: row.f_user_id,
      f_user_name: row.f_user_name,
      f_correct_type: '',
      f_correct_id: model.id,
      f_correct_cause: '购气错误',
      f_correct_money: 0 - model.f_preamount,
      f_correct_state: '有效',
      f_correct_gas: 0 - model.f_pregas,
      f_correct_collection: model.f_collection,
      f_filiale: Util.f.f_fengongsi,
      f_outlets: Util.f.f_parentname,
      f_operator: Util.f.name
    },
    userfiles: {
      f_user_id: model.f_user_id,
      f_meter_base: row.f_meter_base - model.f_pregas,
      f_total_fee: (row.f_total_fee - 0) - (model.f_preamount - 0),
      f_times: row.cardInfo.Times - 1,
      version: row.version
    },
    changeplus: {
      f_user_id: model.f_user_id,
      f_meter_base: row.f_meter_base - model.f_pregas,
      f_remanent_gas: row.f_remanent_gas + model.f_pregas,
      version: row.version
    },
    userinfo: {
      f_userinfo_id: model.f_userinfo_id,
      f_balance: model.f_balance,
      f_real_balance: model.f_balance,
      version: row.userinfo_version
    },
    type: model.f_canceltype,
    id: model.id
  }
  return Vue.resetpost('rs/logic/chargeCancel', {data: data}, {resolveMsg: null, rejectMsg: '冲正卡上气量存库失败'})
}

let getParamGen = function * (id, f_alias) {
  let data = {
    f_card_id: id,
    f_alias: f_alias
  }
  return co(Vue.resetpost('rs/logic/stairCard', {data: data}, {resolveMsg: null, rejectMsg: '获取写卡参数失败'}))
}

let recordCancelGen = function * (model, data) {
  // 获取表档案和户档案参数
  let result = yield co(Vue.resetpost('rs/logic/cardChargeCancel', {data: {model: model, recordData: data}}, {resolveMsg: null, rejectMsg: '获取写卡参数失败'}))

  // 防止表档案和户档案版本号不明确
  result.data.userinfo.userinfo_version = result.data.userinfo.versioin
  // 对数据进行整理
  yield co(sellCancelGen(result.data.sell, Object.assign({}, result.data.userinfo, result.data.userfile)))
}

let chargeCancel = function * (model, data) {
  console.log('收费冲正:..........', model, data)
  // yield Vue.resetpost('rs/sql/', {data: {model: model, correct: correct}}, {resolveMsg: null, rejectMsg: '获取收款失败'})
  let getCollection = yield Vue.resetpost('rs/sql/singleTable', {data: {tablename: 't_sellinggas', condition: `id = '${data.id}'`}}, {resolveMsg: null, rejectMsg: null})
  console.log('获取收款内容.', getCollection.data[0])
  if (getCollection.data.length > 0) {
    let correct = {
      f_user_id: data.f_user_id + '',
      f_user_name: data.f_user_name,
      f_correct_type: '收费冲正',
      f_correct_id: data.id,
      f_correct_cause: model.f_cancel_reason,
      f_correct_money: 0 - getCollection.data[0].f_preamount,
      f_correct_state: '有效',
      f_correct_gas: 0 - getCollection.data[0].f_pregas,
      f_correct_collection: getCollection.data[0].f_collection,
      f_filiale: Util.f.f_fengongsi,
      f_outlets: Util.f.f_parentname,
      f_operator: Util.f.name
    }
    return Vue.resetpost('rs/logic/chargeReverse', {data: {model: model, correct: correct}}, {resolveMsg: '撤销成功', rejectMsg: '撤销失败'})
  } else {
    Vue.showAlert('该记录没有对应的收费记录，请核对数据!!!', 'danger', 0)
  }
}

let CancelService = {
  install (Vue, options) {
    // 给vue增添对话框显示方法
    Vue.CancelService = Vue.prototype.$CancelService = CancelService
  },
  cardChargeCancel (model, row) {
    let cardGen = sellCancelGen(model, row)
    return co(cardGen)
  },
  // 撤销操作
  cancel (url, model, data) {
    // TODO 还有换表补气，和掉气补气两个，（需要将record表中类型换成对应的补气类型）
    if (data.type === '卡表收费' || data.type === '发卡售气') {
      let recordGen = recordCancelGen(model, data)
      return co(recordGen)
    } else if (data.type === '机表收费' || data.type === '自动下账') {
      let chargeGen = chargeCancel(model, data)
      return co(chargeGen)
    } else {
      data.f_user_id = `${data.f_user_id}`
      return Vue.resetpost(url, {data: {model: model, recordData: data, f: Util.f}}, {resolveMsg: '撤销成功', rejectMsg: '撤销失败'})
    }
  }
}

export default CancelService
